package com.xxxx.dao.impl;

import com.xxxx.dao.BaseDao;
import com.xxxx.dao.CourseDao;
import com.xxxx.entity.Course;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class CourseDaoImpl extends BaseDao implements CourseDao {

    @Override
    public int save(Course course) throws Exception {
        String sql="insert into course(cname,classhour) values(?,?)";
        return this.update(sql,course.getCname(),course.getClassHour());
    }

    @Override
    public int del(int cno) throws Exception {
        String sql="delete from course where cno=?";
        return this.update(sql,cno);
    }

    @Override
    public int update(Course course) throws Exception {
        String sql="update course set classHour=? where cno=?";
        return this.update(sql,course.getClassHour(),course.getCno());
    }

    @Override
    public ArrayList<Course> getAll() throws Exception {
        ArrayList<Course> list;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn=this.getConnection();
            String sql="select * from course where classHour>?";
            pstmt = conn.prepareStatement(sql);
            rs= pstmt.executeQuery();
            list = new ArrayList<>();
            while(rs.next())
            {
                Course c=new Course();
                c.setCno(rs.getInt("cno"));
                c.setCname(rs.getString("cname"));
                c.setClassHour(rs.getInt("classHour"));
                list.add(c);
            }
        } finally {
            this.close(rs,pstmt,conn);
        }
        return list;
    }
}
